'''project form'''
from django import forms
from web import models
from utils.form_placeholder import form_placeholder
from django.core.exceptions import ValidationError
from web.forms.widgets import ColorRadioSelect


class add_project(form_placeholder, forms.ModelForm):
    except_bootstrap_styles = ['color']

    class Meta:
        model = models.Project
        fields = ['name', 'color', 'disc']
        labels = {
            'disc': '项目描述'
        }
        widgets = {
            'disc': forms.Textarea(),
            'color': ColorRadioSelect(attrs={'class': 'color-radio'})
        }

    def __init__(self, request, *args, **kwargs):
        super(add_project, self).__init__(*args, **kwargs)
        self.request = request

    def clean_name(self):
        # 查询当前用户是否使用当前名字
        name = self.cleaned_data.get('name')
        exist = models.Project.objects.filter(name=name, creator=self.request.tracer.user).exists()
        if exist:
            raise ValidationError('该项目名已经存在')
        # 判断是否还有额度
        # 获取当前用户套餐，项目额度
        policy_num = self.request.tracer.Price_Policy.project_count
        # 获取当前项目的个数
        current_num = models.Project.objects.filter(creator=self.request.tracer.user).count()
        if policy_num <= current_num:
            raise ValidationError('额度不足，请升级套餐')
        return name
